package com.tinshow.config.cookie;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinshow.model.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.web.bind.annotation.CookieValue;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * Created by libo4 on 2017-05-14.
 */
public class CookieUtil implements Serializable{


    public static void setCookie(String name , String value, HttpServletResponse response){
        Cookie cookie = new Cookie(name,value);
        cookie.setMaxAge(60 * 60 * 24 * 7);
        response.addCookie(cookie);
    }

    public static String getCookie(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie: cookies){
                if(cookie.getName().equals("JSESSIONID")){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static void setSession(User user,HttpServletRequest request,HttpServletResponse response) throws Exception{
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        session.setMaxInactiveInterval(60 * 60 * 24 * 7);
        String jsessionId = session.getId();
        setCookie("SESSION", jsessionId, response);
    }

    public static JSONObject getSession(HttpServletRequest request){
        JSONObject jsonObject = null;
        try {
            HttpSession session = request.getSession();
            Object value = session.getAttribute("user");

            if (value != null) {
                jsonObject = (JSONObject) JSON.toJSON(value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

}
